package com.whfc.openapi.api.sys.controller;

import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.entity.dto.login.MsUserLogin;
import com.whfc.fuum.dto.open.AccessCodeDTO;
import com.whfc.fuum.dto.open.AccessTokenDTO;
import com.whfc.fuum.dto.open.OpenApiClientDTO;
import com.whfc.fuum.param.open.AccessTokenParam;
import com.whfc.fuum.param.open.OpenApiTokenParam;
import com.whfc.openapi.constant.OpenApiConst;
import com.whfc.openapi.api.sys.service.OpenApiTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/10/21 11:34
 */
@RestController
@RequestMapping(value = "open/api")
public class OpenApiTokenController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OpenApiTokenService openApiTokenService;

    /**
     * 获取accessToken(旧接口)
     *
     * @param param
     * @return
     */
    @Deprecated
    @PostMapping(value = "accessToken")
    public Result getAccessToken(@RequestBody AccessTokenParam param) {
        logger.info("获取accessToken,param:[{}]", param);
        AccessTokenDTO accessTokenDTO = openApiTokenService.getAccessToken(param);
        return ResultUtil.success(accessTokenDTO);
    }

    /**
     * 获取accessToken(v1)
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/v1/auth/token")
    public Result getOpenApiToken(@RequestBody OpenApiTokenParam param) {
        logger.info("获取openApiToken,param:[{}]", param);
        AccessTokenDTO accessTokenDTO = openApiTokenService.getOpenApiToken(param);
        return ResultUtil.success(accessTokenDTO);
    }

    /**
     * 获取免密登录授权码
     *
     * @param openApiClientDTO
     * @param username
     * @param phone
     * @return
     */
    @GetMapping("/v1/auth/code")
    public Result getCode(@RequestAttribute(OpenApiConst.OPENAPI_CLIENT) OpenApiClientDTO openApiClientDTO,
                          @RequestParam("username") String username,
                          @RequestParam("phone") String phone) {
        Integer deptId = openApiClientDTO.getDeptId();
        logger.info("获取code,deptId:{},username:{},phone:{}", deptId, username, phone);
        AccessCodeDTO data = openApiTokenService.getCode(deptId, username, phone);
        return ResultUtil.success(data);
    }

    /**
     * 获取免密登录授权码
     *
     * @param user
     * @return
     */
    @PostMapping("/v1/auth/checkUser")
    public Result checkUser(@RequestBody @Validated MsUserLogin user) {
        logger.info("校验账号密码是否正确,user:{}", user);
        openApiTokenService.checkUser(user);
        return ResultUtil.success();
    }
}
